import gupiaoDao from "../Dao/gupiao.js";
import {httpResult} from "../utils/utils.js";
import gupiaoListDao from "../Dao/gupiaoList.js";
import sequelize from "../models/init.js";
import gupiaoUpdateDao from "../Dao/gupiao_update.js";
// import {getPriceAndName} from "../utils/gupiaoUtils.js";
import {getPriceGuPiao} from "../api/api_gupiao/useGuPiao.js";


// 获取用户所有在收集的信息 http://127.0.0.1:52000/gp/getallgp?user_id=1
export const getUserAll = async (req, res, next) => {
  let {user_id} = req.query;
  if (!user_id) {
    throw new Error("请传入正确的id");
  }
  let result = await gupiaoDao.getUserGuPiaoAll(user_id);
  let gupiaoList = await gupiaoListDao.get();
  result.rows.forEach(item => {
    item.gupiao_name = gupiaoList.find(gp => gp.gupiao_id === item.gupiao_id).gupiao_name;
    item.gupiao_price = gupiaoList.find(gp => gp.gupiao_id === item.gupiao_id).gupiao_price;
  });
  // console.log(gupiaoList, result);
  res.send(httpResult.success(result));
};
// 获取用户IP
export const getUserIp = async (req, res, next) => {
  const result = {
    'x-forwarded-for': req.header('x-forwarded-for'),
    'ips': req.ips,
    'remoteAddress': req.connection.remoteAddress,
    'ip': req.ip
  };
  // console.log(gupiaoList, result);
  res.send(httpResult.success(result));
};

// 用户添加新的股票监控 http://127.0.0.1:52000/gp/addgp?user_id=1&gupiao_id=601398&price_buy=4.5&price_sell_high=5
export const addGuPiao = async (req, res, next) => {
  let {user_id, gupiao_id, price_buy, price_sell_high, price_sell_low} = req.query;
  checkId(user_id, gupiao_id);
  if (!price_buy) {
    throw  new Error("请传入正确的参数");
  }
  // 如果未输入卖出的高低价 则按照股票的购买价格计算 85%-110%
  if (!price_sell_low) {
    price_sell_low = Math.round(price_buy * 85) / 100;
  }
  if (!price_sell_high) {
    price_sell_high = Math.round(price_buy * 110) / 100;
  }
  // 添加股票和增加搜索股票
  const t = await sequelize.transaction();
  try {
    await gupiaoDao.addNewGuPiao(user_id, gupiao_id, price_buy, price_sell_high, price_sell_low, t);
    await gupiaoListDao.add(gupiao_id, t);
    await t.commit();
    updateGuPiaoData(gupiao_id);
  } catch (e) {
    await t.rollback();
    throw new Error('添加失败');
  }
  res.json(httpResult.success('添加成功'));
};

// 修改用户的股票设置信息 http://127.0.0.1:52000/gp/updategp?user_id=1&gupiao_id=601398&price_sell_low=5.2
export const updateUserGuPiao = async (req, res, next) => {
  let {user_id, gupiao_id, price_buy, price_sell_high, price_sell_low, do_it, limit_time} = req.query;
  limitTimeCheck(limit_time);
  checkId(user_id, gupiao_id);
  // 检查是否真的进行修改
  let preData = await gupiaoDao.getUserGuPiao(user_id, gupiao_id);
  checkUpdate(preData, price_buy, price_sell_high, price_sell_low, do_it);
  // 修改股票数据和增加股票修改记录
  const t = await sequelize.transaction();
  try {
    await gupiaoDao.updateGuPiao(user_id, gupiao_id, price_buy, price_sell_high, price_sell_low, do_it, t);
    // 在修改价格的时候记录修改历史
    if (price_buy || price_sell_high || price_sell_low) {
      await gupiaoUpdateDao.addGupiaoUpdate(user_id, gupiao_id, preData.price_buy, preData.price_sell_high, preData.price_sell_low, t);
    }
    await t.commit();
  } catch (e) {
    console.log(e, 'updateUserGuPiao');
    await t.rollback();
    throw new Error('更新失败');
  }
  res.json(httpResult.success('更新成功'));
};

// 用户删除股票信息 http://127.0.0.1:52000/gp/deletegp?user_id=1&gupiao_id=601398
export const deleteUserGuPiao = async (req, res, next) => {
  let {user_id, gupiao_id} = req.query;
  checkId(user_id, gupiao_id);
  const t = await sequelize.transaction();
  try {
    await gupiaoDao.deleteGuPiao(user_id, gupiao_id, t);
    let count = await gupiaoDao.getUserGuPiaoCount(gupiao_id, t);
    if (count === 0) {
      await gupiaoListDao.delete(gupiao_id, t);
    }
    await t.commit();
  } catch (e) {
    console.log(e, 'deleteUserGuPiao');
    await t.rollback();
    throw new Error('删除失败');
  }
  res.json(httpResult.success('删除成功'));
};

// 用户id和股票id检测
const checkId = (user_id, gupiao_id) => {
  if (!user_id || !gupiao_id) {
    throw new Error("请输入正确的id");
  }
};

// 检测过期时间
const limitTimeCheck = (limit_time) => {
  if (!limit_time) {
    return;
  }
  if (limit_time > new Date().getTime()) {
    throw new Error("链接已过期");
  }
};

// 当某一项不为undefined 这项值就不应该等于之前的数据 如果所有的数据不是undefined就是等于之前的数据那就是没有修改
const checkUpdate = (preData, price_buy, price_sell_high, price_sell_low, do_it) => {
  console.log(preData, price_buy, price_sell_high, price_sell_low, do_it, 'checkUpdate');
  if (price_buy !== undefined && +price_buy !== preData.price_buy) {
    return true;
  }
  if (price_sell_high !== undefined && +price_sell_high !== preData.price_sell_high) {
    return true;
  }
  if (price_sell_low !== undefined && +price_sell_low !== preData.price_sell_low) {
    console.log(preData.price_sell_low, price_sell_low, 'price_sell_low', price_sell_low !== preData.price_sell_low, typeof price_sell_low, typeof preData.price_sell_low);
    return true;
  }
  if (do_it !== undefined && +do_it !== preData.do_it) {
    return true;
  }
  throw new Error('没有修改');
};

// 存储用户股票后 异步存储用户新增的股票的名称和价格
const updateGuPiaoData = async (gupiao_id) => {
  let {price, name, result} = await getPriceGuPiao(gupiao_id);
  // let {price, name} = await getPriceAndName(gupiao_id);
  let gupiao_name = name;
  let gupiao_price = price;
  await gupiaoListDao.update(gupiao_id, gupiao_name, gupiao_price);
};
